package com.chongzi.cloud;



import java.util.HashMap;

class LRUCache {
    private int capacity;
    private HashMap<Integer, Node> map=new HashMap<>();
    private DoubleLinkedList list=new DoubleLinkedList();




    public LRUCache(int capacity) {
        this.capacity=capacity;
    }

    public int get(int key) {
        if (!map.containsKey(key)){
            return -1;
        }
        Node n = map.get(key);
        list.remove(n);
        list.addFist(n);
        return n.value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)){
            Node n = map.get(key);
            n.value=value;
            list.remove(n);
            list.addFist(n);
        }else {
            Node n = new Node(key, value);
            list.addFist(n);
            map.put(key,n);
            if (map.size()>capacity){
                Node lastNode=list.removeLast();
                map.remove(lastNode.key);
            }
        }
    }


}

class Node {
    int key;
    int value;
    Node prev;
    Node next;

    Node() {
        this.key = key;
        this.value = value;
    }

    Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

class DoubleLinkedList {
    Node head;
    Node tail;

    DoubleLinkedList() {
        head = new Node(0, 0);
        tail = new Node(0, 0);
        head.next=tail;
        tail.prev=head;

    }
    void addFist(Node node){
        node.next=head.next;
        head.next.prev=node;
        node.prev=head;
        head.next=node;



    }
    void remove(Node node){
        node.prev.next=node.next;
        node.next.prev=node.prev;
    }
    Node removeLast(){
       Node lastNode=tail.prev;
       remove(lastNode);
       return lastNode;

    }

}


